package com.gykj.tap.service.impl;

import org.springframework.stereotype.Service;

import com.gykj.tap.service.BaseService;
import com.gykj.tap.service.IFanService;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.msg.WriteCoilRequest;
import com.serotonin.modbus4j.msg.WriteCoilResponse;

@Service("fanService")
public class FanServiceImpl extends BaseService implements IFanService  {

	@Override
	public Boolean readCoilStatus(String host, int port, int slaveId, int offset)
			throws ModbusTransportException, ErrorResponseException,
			ModbusInitException {
		// 01 Coil Status
		BaseLocator<Boolean> loc = BaseLocator.coilStatus(slaveId, offset);
		Boolean value = getMaster(host,port).getValue(loc);
		return value;
	}

	@Override
	public boolean writeCoil(int slaveId, int writeOffset, boolean writeValue,
			String host, int port) throws ModbusTransportException,
			ModbusInitException {
		// 获取master
		ModbusMaster tcpMaster = getMaster(host,port);
		// 创建请求
		WriteCoilRequest request = new WriteCoilRequest(slaveId, writeOffset, writeValue);
		// 发送请求并获取响应对象
		WriteCoilResponse response = (WriteCoilResponse) tcpMaster.send(request);
		if (response.isException()) {
			return false;
		} else {
			return true;
		}
	}
}
